package com.bourse.core.services.cotation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.bourse.core.exceptions.TimeSerieException;
import com.bourse.core.ibatis.IndiceCompoDao;
import com.bourse.core.utils.IndiceComposition;
import com.bourse.core.utils.IsinCode;
import com.bourse.core.utils.TimeSerieObject;
import com.googlecode.ehcache.annotations.Cacheable;

public class IndiceCompoDataServiceImpl implements IndiceCompoDataService {
	
	private Logger LOGGER = Logger.getLogger(IndiceCompoDataServiceImpl.class);
	
	private IndiceCompoDao indiceCompoDao;
	
	/**
	 * @see IndiceCompoDataServiceImpl#insertIndiceComposition(List)
	 */
	public void insertIndiceComposition(List<IndiceComposition> indiceCompo) {
		indiceCompoDao.insertIndiceCompo(indiceCompo);
	}

	/**
	 * @see IndiceCompoDataServiceImpl#getIndiceComposition()
	 */
	@Cacheable(cacheName="indiceComposition")
	public Map<IsinCode,TimeSerieObject<List<IsinCode>>> getIndiceComposition() {
		
		List<IndiceComposition> indiceCompoList = indiceCompoDao.getIndiceCompo();
		Map<IsinCode,TimeSerieObject<List<IsinCode>>> compositionMap = new HashMap<IsinCode, TimeSerieObject<List<IsinCode>>>();
		
		LOGGER.error("[Indice Compo] - Building composition map "); 
		for(IndiceComposition composition : indiceCompoList){
			IsinCode indice = composition.getIsinIndice();
			TimeSerieObject<List<IsinCode>> compoTs = compositionMap.get(indice);
			if (compoTs == null) {
				compoTs = new TimeSerieObject<List<IsinCode>>();
				compositionMap.put(indice, compoTs);
			}
			
			try {
				List<IsinCode> codeList = compoTs.getValue(composition.getDate());
				if (codeList==null) {
					codeList = new ArrayList<IsinCode>();
					compoTs.add(composition.getDate(), codeList);
				}
				codeList.add(composition.getIsin());
			} catch(TimeSerieException e){
				LOGGER.error("[Indice Compo] - Error while getting datas: "+e.getMessage());
			}
		}
		return compositionMap;
	}
	
	/**
	 * @param indiceCompoDao
	 *            the indiceCompoDao to set
	 */
	public void setIndiceCompoDao(IndiceCompoDao indiceCompoDao) {
		this.indiceCompoDao = indiceCompoDao;
	}

}
